<?php
  require_once('./db.php');

  $file = $_SERVER['PHP_SELF'];
  $id = isset($_GET['id'])?$_GET['id']:0;
  $msg = '';
  //?status=0&mode=status&id=5
  if(isset($_GET['mode']) &&
  $_GET['mode']=='status') {
    $newStatus = $_GET['status']==1?0:1;
    $updateData =  array('status'=>$newStatus);
    $affectedRows = update('users',"`id`='$id'",$updateData);

    if($affectedRows == 1){
      $msg = 'Status updated  successfully';
    }
  }
  if(isset($_GET['mode']) &&
  $_GET['mode']=='del') {

    $deletedRows = delete('users', "`id`='$id'");
    if($deletedRows == 1){
      $msg = "Record Deleted Successfully";
    }
  }

  # Calculate Total Number of USers

  $totalUser = countAll('users');
  $rpp = 2;# record per page
  $totalPages = ceil($totalUser / $rpp);
  $curPage = isset($_GET['page']) ? $_GET['page'] : 1;
  $limit = ($curPage - 1) * $rpp;

  $result = fetchAll('users','','','',"$limit, $rpp");

?>

<h4><em><?=$msg?></em></h4>

<table  border="1" cellpadding="0" cellspacing="0" width="80%" align="center">
  <thead>
    <tr>
      <th colspan="6">:: All Users  ::</th>
    </tr>
    <tr>
      <th align="left">#</th>
      <th align="left">Name</th>
      <th align="left">Email</th>
      <th align="left">Avatar</th>
      <th align="left">Added date</th>
      <th align="left">Status</th>
      <th align="left">Action</th>
    </tr>
  </thead>
  <tbody>
<?php
  while($ans = mysql_fetch_assoc($result))
  {
    $id = $ans['id'];
    $status = $ans['status'];
    $imagePath = "uploads/".$ans['avatar'];
?>
    <tr>
      <td><?=$id?></td>
      <td><?=$ans['name']?></td>
      <td>

        <a href="mailto:<?=$ans['email']?>"><?=$ans['email']?></a>
      </td>
      <td><img height="90" width="120" src="<?=$imagePath?>"></td>

      <td><?=date('d-M-Y G:i a',strtotime($ans['added_date']))?></td>

      <td>
        <a href="<?=$file?>       ?status=<?=$status?>&mode=status&id=<?=$id?>">
        <a href="display_users.php?status=     1      &mode=status&id=   2">    
        <?=getStatus($status)?>
        </a>
      </td>

      <td>

      <a target="_blank" href="edit_user.php?id=<?=$id?>">Edit</a> /

      <a onClick="return confirm('Are you sure ?');" href="display_users.php?id=<?=$id?>&mode=del">Delete</a>

      </td>
    </tr>
<?php
  }// end while
?>

  </tbody>
</table>

<table  border="1" cellpadding="0" cellspacing="0" width="80%" align="center">
    <tr>
<?php
  for($i=1 ; $i<=$totalPages ;$i++)
  {
?>
      <th>

<?php
  if($curPage == $i){
    echo '<span style="font-size:25px;color:red">'.$i.'</span>';
  } else { // end if
   echo "<a href='$file?page=$i'>$i</a>";

  }//end else
?>


      </th>
<?php
  }
?>
    </tr>

</table>
<?php
  require_once("footer.php");
?>
